#!/usr/bin/python

#-------------------------------------------------------------------------------
# Name:        updateserver
# Purpose:     To update steamcmd based games to the current version.
#
# Author:      Donald L Talbert , www.bwhgaming.com
#
# Created:     20/09/2012
# Copyright:   (c) Donald L Talbert 2012
# Licence:     MIT
#-------------------------------------------------------------------------------

# Import builtin modules
import os
import logging
import subprocess
import shlex
import re
import time

# Import my modules
import loadconfig


class UpdateServer(object):
    """
    This class handles everything regarding updating the server.
    """
    def __init__(self):
        """
        Loads options from the config and sets the directories to
        update and also prepares some varables to be used.

        """
        # Load config options.
        lc = loadconfig.LoadConfig()
        self.updateDir = lc.updateDirectory
        self.serverDir = lc.serverDirectory
        self.command = lc.command

		# preparing the update command to a list for subprocess
        prepBinPath = self.updateDir + "/" + self.command
        self.binPath = shlex.split(prepBinPath)


    def Update(self):
        """
        This method launches the actual updater and updates the
        server then it returns the output to be analyized.
        """
        target = subprocess.Popen(self.binPath, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
        strOutput = target.stdout.read()
        #logging.debug(strOutput)
        #logging.debug(self.binPath)
        return strOutput

    def checkIfAlreadyUpdated(self, strText):
        """
        Checks if server is already updated and returns a bool.
        True = Already updated, False = server was updated.
        """
        listSearch = ["Success! App '212542' fully installed.", "Success! App '212542' already up to date."] #Might be platform dependant. Says Updated on Linux.
        output = strText

        for item in listSearch:
            match = re.search(item, output)
            if match:
                logging.info("Server is already update to date.")
                return True

        logging.info("Server has been updated.")
        logging.debug(output)
        return False


    def Main(self):
        """
        This kicks off the entire update process. First by storing
        the output of the update and sending it to a method to
        anaylize it. Returns a bool if the server was updated.
        """
        output = self.Update()
        bReturn = self.checkIfAlreadyUpdated(output)
        return bReturn

if __name__ == '__main__':
    pass
